package com.matrix.draft.sockettest.protocoltcp;

import com.matrix.draft.sockettest.protocoltcp.handler.ProtocolDecoder;
import com.matrix.draft.sockettest.protocoltcp.handler.ProtocolEncoder;
import com.matrix.draft.sockettest.protocoltcp.handler.ServerHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

/**
 * TCP粘包拆包问题解决
 */
public class ProtocolMsgServer {
    private String host = "127.0.0.1";
    private Integer port = 8080;

    public void run(){
        EventLoopGroup bossGroup = new NioEventLoopGroup(1);
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            new ServerBootstrap().group(bossGroup,workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .option(ChannelOption.SO_BACKLOG,128)
                    .childOption(ChannelOption.SO_KEEPALIVE,true)
                    .childHandler(new ChannelInitializer<NioSocketChannel>() {
                        @Override
                        protected void initChannel(NioSocketChannel ch) throws Exception {
                            ChannelPipeline pipeline = ch.pipeline();
                            // Out
                            pipeline.addLast(new ProtocolEncoder());
                            // In
                            pipeline.addLast(new ProtocolDecoder());
                            pipeline.addLast(new ServerHandler());
                        }
                    })
                    .bind(host,port)
                    .addListener(future -> {
                        if(future.isSuccess()){
                            System.err.println("自定义协议粘包拆包服务器已启动...");
                        }
                    })
                    .sync().channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }

    public static void main(String[] args) {
        new ProtocolMsgServer().run();
    }
}
